package store

import (
	"gitee.com/zaiqiang231/lovesport-user-service/app/model"
	"gorm.io/gorm"
	"reflect"
)

type PolicyStore struct {
	db *gorm.DB
}

type PolicyListOptions struct {
	Page     int `form:"page"`
	PageSize int `form:"pagesize"`
}

func (s *PolicyStore) Create(m *model.Policy) error {
	err := s.db.
		Create(&m).Error
	if err != nil {
		return err
	}
	return nil
}

func (s *PolicyStore) Update(m *model.Policy) error {
	err := s.db.
		Save(&m).Error
	if err != nil {
		return err
	}
	return nil
}

func (s *PolicyStore) Get(username string, name string) (*model.Policy, error) {
	m := &model.Policy{}
	err := s.db.
		Where("username = ? and name = ?", username, name).
		First(&m).Error
	if err != nil {
		return nil, err
	}
	return m, nil
}

func (s *PolicyStore) Delete(username string, name string, isSoftDelete bool) error {
	m := &model.Policy{}
	var err error
	if isSoftDelete {
		err = s.db.
			Where("username = ? and name = ?", username, name).
			Delete(&m).Error
	} else {
		err = s.db.
			Where("username = ? and name = ?", username, name).
			Unscoped().
			Delete(&m).Error
	}

	if err != nil {
		return err
	}
	return nil
}

func (s *PolicyStore) List(opts PolicyListOptions, username string) (*PolicyList, error) {
	list := &PolicyList{}
	var err error
	db := s.db
	if username != "" {
		db = db.Where("username = ?", username)
	}
	if !reflect.DeepEqual(opts, PolicyListOptions{}) {
		err = db.
			Offset((opts.Page - 1) * opts.PageSize).
			Limit(opts.PageSize).
			Find(&list.List).
			Offset(-1).
			Limit(-1).
			Count(&list.Total).Error
	} else {
		err = db.Table("policy").
			Offset(-1).
			Limit(-1).
			Unscoped().
			Find(&list.List).
			Count(&list.Total).Error
	}

	if err != nil {
		return nil, err
	}
	return list, nil
}

type PolicyList struct {
	Total int64          `json:"total"`
	List  []model.Policy `json:"list"`
}
